﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using MyFloridaHouse.ServiceConn.DistrBldrSvcRef;
using System.Windows;

namespace MyFloridaHouse.libSvOpenDistricts.StorageIsolated
{
    public static class IsolatedStorageManager
    {

        public static bool SaveData(string data, string directoryName, string fileName)
        {
            try
            {
                CreateDirectory(directoryName);
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
                {
                    using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
                    {
                        using (StreamWriter sw = new StreamWriter(isfs))
                        {
                            sw.Write(data);
                            sw.Close();
                        }
                    }
                }
                return true;
            }
            catch (IsolatedStorageException ex)
            {
                //todo: log error here when save data to storage fails
                IsolatedStorageManager.Deletefile(directoryName, fileName); //Leave for debug clearing of files
                return false;
            }
        }

        public static bool SaveData(byte[] data, string directoryName, string fileName)
        {
            try
            {
                CreateDirectory(directoryName);
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
                {
                    if (!CheckStorageSize(data.Length))
                    {
                        IsolatedStorageIncreaseDialog increaseDlg = new IsolatedStorageIncreaseDialog();
                        increaseDlg.SaveToIsolatedStorageWithDialog(directoryName, fileName, false, "", data);
                    }
                    else
                    {
                        using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(Path.Combine(directoryName, fileName), FileMode.Create, isf))
                        {
                            using (BinaryWriter sw = new BinaryWriter(isfs))
                            {
                                sw.Write(data);
                                sw.Close();
                            }
                        }
                    }
                }
                return true;
            }
            catch (IsolatedStorageException ex)
            {
                //todo: log error here when save data to storage fails
                IsolatedStorageManager.Deletefile(directoryName, fileName); //Leave for debug clearing of files
                return false;
            }
        }

        public static bool CheckStorageSize(Int64 sizeToCheckFor)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
            {
                try
                {
                    Int64 currAval = isf.AvailableFreeSpace;
                    if (sizeToCheckFor < currAval)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (IsolatedStorageException ex)
                {
                    //todo: log error here when save data to storage fails
                    throw ex;
                }
            }

        }



        public static string LoadStringData(string directoryName, string fileName)
        {
            string fullFileName = Path.Combine(directoryName, fileName);
            string data = String.Empty;
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fullFileName, FileMode.Open, isf))
                {
                    using (StreamReader sr = new StreamReader(isfs))
                    {
                        string lineOfData = String.Empty;
                        while ((lineOfData = sr.ReadLine()) != null)
                            data += lineOfData;
                    }
                }
            }
            return data;
        }

        public static byte[] LoadBinaryData(string directoryName, string fileName)
        {
            string fullFileName = Path.Combine(directoryName, fileName);
            byte[] data = null;
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fullFileName, FileMode.Open, isf))
                {
                    data = new byte[isfs.Length];
                    isfs.Read(data, 0, Convert.ToInt32(isfs.Length));
                    isfs.Close();
                }
            }
            return data;
        }

        public static List<string> GetDirectories()
        {
            List<string> directoryList = new List<string>();
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
            string[] directories = isf.GetDirectoryNames("*");
            foreach (var dir in directories)
            {
                directoryList.Add(dir);
            }
            return directoryList;
        }

        public static bool DirectoryExists(string directoryName)
        {
            List<string> fileList = GetDirectories();
            var fileListCount = (from fil in fileList
                                 where fil == directoryName
                                 select fil).Count();
            if (fileListCount == 1)
                return true;
            else
                return false;
        }

        public static DateTime GetFileCreationTime(string directoryName, string fileName)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
            return (isf.GetCreationTime(directoryName + "\\" + fileName)).UtcDateTime;
        }

        public static bool FileExists(string directoryName, string fileName)
        {
            List<string> fileList = GetFilesInSubDirectory(directoryName, fileName);
            if (fileList.Count > 0)
                return true;
            else
                return false;
        }

        public static List<string> GetFilesInSubDirectory(string subDirectoryName, string fileName)
        {

            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
            List<string> fileList = new List<string>();
            string searchpath = Path.Combine(subDirectoryName, fileName);

            string[] directoriesInTheRoot = isf.GetDirectoryNames();
            string[] filesInTheRoot = isf.GetFileNames();
            string[] filesInSubDirs = isf.GetFileNames(searchpath);

            string[] files = isf.GetFileNames(searchpath);
            foreach (var fil in files)
            {
                fileList.Add(fil);
            }
            //IsolatedStorageManager.Deletefile(subDirectoryName + "\\" + fileList[0]); //Leave for debug clearing of files
            return fileList;
        }

        public static void DeleteFilesInSubdirectory(string subDirectoryName)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
            String[] fileNames = isf.GetFileNames(subDirectoryName + "\\*");

            if (fileNames.Length > 0)
            {
                for (int i = 0; i < fileNames.Length; ++i)
                {
                    // Delete the files.
                    isf.DeleteFile(subDirectoryName + "\\" + fileNames[i]);
                }
                // Confirm that no files remain.
                fileNames = isf.GetFileNames(subDirectoryName + "\\*");
            }

        }

        public static List<string> GetFilesInRootDirectory(string directoryName)
        {
            List<string> fileList = new List<string>();
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
            string[] files = isf.GetFileNames(directoryName + "\\*");
            foreach (var fil in files)
            {
                fileList.Add(fil);
            }
            return fileList;
        }

        public static void CreateDirectory(string directoryName)
        {
            if (!DirectoryExists(directoryName))
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
                isf.CreateDirectory(directoryName);
            }
        }

        public static void DeleteDirectory(string directoryName)
        {
            if (DirectoryExists(directoryName))
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
                isf.DeleteDirectory(directoryName);
            }
        }

        public static void Deletefile(string subDirectoryName, string fileName)
        {
            if (FileExists(subDirectoryName, fileName))
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite();
                isf.DeleteFile(subDirectoryName + "\\" + fileName);
            }
        }

        //public static void GetFileInfo(string directoryName, string filter, ObservableCollection<FileInfoDTO> isolatedStorageCollection)
        //{
        //    IsolatedStorageManager.CreateDirectory(directoryName);
        //    isolatedStorageCollection.Clear();

        //    // Gather file information
        //    //string[] directoriesInTheRoot = IsolatedStorageManager.GetDirectoryNames();
        //    //string[] filesInTheRoot = IsolatedStorageManager.GetFileNames();
        //    //string searchpath = Path.Combine("DistrictPlans", "*.*");
        //    //string[] filesInSubDirs = IsolatedStorageManager.GetFilesInSubDirectory(searchpath);


        //    List<string> fileNameList = IsolatedStorageManager.GetFilesInSubDirectory(directoryName,filter);
        //    foreach (var fullFileName in fileNameList)
        //    {
        //        FileInfoDTO fileInfo = new FileInfoDTO();
        //        fileInfo.fileName= fullFileName.Split('.')[0];
        //        isolatedStorageCollection.Add(fileInfo);
        //    }

        //}




        internal static bool ReserveStorageSpace(Int64 bytesToReserve)
        {
            Int64 MbytesToReserve = bytesToReserve / 1000000;

            if (IsolatedStorageManager.CheckStorageSize(bytesToReserve))
            {
                return true;
            }
            else
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite())
                {
                    try
                    {
                       // MessageBox.Show("Increasing isolated storage by " + bytesToReserve / 1000000 + "M " );
                        if (isf.IncreaseQuotaTo(isf.Quota + bytesToReserve))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (IsolatedStorageException ex)
                    {
                        MessageBox.Show("Unable reserve file space in local isolated storage " + ex.Message);
                        return false;
                    }
                }
            }
        }


    }
}
